package com.pig4cloud.pig.module.controller.wmj;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.pig4cloud.pig.common.core.util.QRCodeUtilEx;
import com.pig4cloud.pig.common.core.util.R;
import com.pig4cloud.pig.common.log.annotation.SysLog;
import com.pig4cloud.pig.common.mybatis.page.PageUtils;
import com.pig4cloud.pig.common.mybatis.page.TableDataInfo;
import com.pig4cloud.pig.module.api.entity.wmj.WmjDoor;
import com.pig4cloud.pig.module.service.wmj.IWmjDoorService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import javax.validation.constraints.NotEmpty;
import javax.validation.constraints.NotNull;
import java.util.Arrays;
import java.util.List;

/**
 * 微门禁列Controller
 *
 * @author ruoyi
 * @date 2022-12-08
 */
@Validated
@Api(value = "微门禁列控制器", tags = {"微门禁列管理"})
@RequiredArgsConstructor(onConstructor_ = @Autowired)
@RestController
@RequestMapping("/wmj/door")
public class WmjDoorController {

    private final IWmjDoorService wmjDoorService;

    @Value("${ruoyi.profile}")
    private String uploadPath;
    @Value("${ruoyi.imgUrl}")
    private String imgUrl;


    /**
     * 查询微门禁列列表
     */
    @ApiOperation("查询微门禁列列表")
    @PreAuthorize("@pms.hasPermission('module:wmjDoor:list')")
    @GetMapping("/list")
    public TableDataInfo<WmjDoor> list(@Validated WmjDoor wmjDoor) {
        QueryWrapper<WmjDoor> qw = new QueryWrapper<>();
        if(StrUtil.isNotEmpty(wmjDoor.getDeviceSn())){
        	qw.like("device_sn", wmjDoor.getDeviceSn());
		}
        TableDataInfo<WmjDoor> td = PageUtils.buildDataInfo(wmjDoorService.page(PageUtils.buildPage(),qw));
        List<WmjDoor> list = td.getData();
        if(CollUtil.isNotEmpty(list)){
        	for (WmjDoor door : list){
				door.setQrCodeUrl(imgUrl + door.getQrCodeUrl());
			}
		}
        return td;
    }

    /**
     * 导出微门禁列列表
     */
    @ApiOperation("导出微门禁列列表")
    @PreAuthorize("@pms.hasPermission('module:wmjDoor:export')")
    @SysLog("微门禁列")
    @GetMapping("/export")
    public List export(@Validated WmjDoor wmjDoor) {
        List<WmjDoor> list = wmjDoorService.list();
        // ExcelUtil<WmjDoor> util = new // ExcelUtil<WmjDoor>(WmjDoor.class);
        return  list;// util.exportExcel(list, "微门禁列");
    }

    /**
     * 获取微门禁列详细信息
     */
    @ApiOperation("获取微门禁列详细信息")
    @PreAuthorize("@pms.hasPermission('module:wmjDoor:query')")
    @GetMapping("/{id}")
    public R<WmjDoor> getInfo(@NotNull(message = "主键不能为空") @PathVariable("id") Long id) {
        WmjDoor wmjDoor = wmjDoorService.getById(id);
        return R.ok(wmjDoor);
    }


    /**
     * 重置二维码
     */
    @SysLog("重置二维码")
    @PostMapping("/resetQrCode")
    @ResponseBody
    @PreAuthorize("@pms.hasPermission('module:wmjDoor:edit')")
    public R<Void> resetQrCode(@RequestBody WmjDoor wmjDoor) {
        if(wmjDoor.getId()!=null){
            try{
                wmjDoor = wmjDoorService.getById(wmjDoor.getId());

                String qrCode = "";
                String fileName = "door_qr_" + wmjDoor.getId() + ".jpg";
                String content = "https://www.sdyuedou.com/wxmini/wmj/info?id=" + wmjDoor.getId();
                int upload_type = 0;// FileUploadUtils.TYPE_WMJ;
                System.out.println("content:  "+ content);
                String img_key = "";// FileUploadUtils.getUploadPrefix(upload_type) + fileName;

                QRCodeUtilEx.createQrCodeImg(content, "", null, uploadPath +"/"+img_key, true, fileName, upload_type);
                qrCode = img_key;
                wmjDoor.setQrCodeUrl(qrCode);
//                WmjUtil.lcdConfig(wmjDoor.getAppId(),wmjDoor.getAppSecret(),wmjDoor.getDeviceSn(), content);
            }catch (Exception ex){
                ex.printStackTrace();
            }
            if (wmjDoorService.updateById(wmjDoor)) {
                return R.ok();
            }
        }
        return R.failed();
    }


    /**
     * 新增微门禁列
     */
    @ApiOperation("新增微门禁列")
    @PreAuthorize("@pms.hasPermission('module:wmjDoor:add')")
    @SysLog("微门禁列")

    @PostMapping()
    public R<Void> add(@Valid @RequestBody WmjDoor wmjDoor) {
		wmjDoor.setAppId("wmj_RnzWTPoIneb");
		wmjDoor.setAppSecret("08qrzQXUi8xuxzMWjBJDgAxvOUJJ6Su0");
        boolean bl = wmjDoorService.save(wmjDoor);
        if(bl){
            try{
                String qrCode = "";
                String fileName = "door_qr_" + wmjDoor.getId() + ".jpg";
                String content = "https://www.sdyuedou.com/wxmini/wmj/info?id=" + wmjDoor.getId();
                int upload_type = 0;//FileUploadUtils.TYPE_WMJ;
                System.out.println("content:  "+ content);
                String img_key = "";//FileUploadUtils.getUploadPrefix(upload_type) + fileName;

                QRCodeUtilEx.createQrCodeImg(content, "", null, uploadPath + "/" + img_key, true, fileName, upload_type);
                qrCode = img_key;
                wmjDoor.setQrCodeUrl(qrCode);
//                WmjUtil.lcdConfig(wmjDoor.getAppId(),wmjDoor.getAppSecret(),wmjDoor.getDeviceSn(), content);
            }catch (Exception ex){
                ex.printStackTrace();
            }
            if (wmjDoorService.updateById(wmjDoor)) {
                return R.ok();
            }
        }

        return R.okByRow(bl ? 1 : 0);
    }

    /**
     * 修改微门禁列
     */
    @ApiOperation("修改微门禁列")
    @PreAuthorize("@pms.hasPermission('module:wmjDoor:edit')")
    @SysLog("微门禁列")

    @PutMapping()
    public R<Void> edit(@Valid @RequestBody WmjDoor wmjDoor) {
		wmjDoor.setAppId("wmj_RnzWTPoIneb");
		wmjDoor.setAppSecret("08qrzQXUi8xuxzMWjBJDgAxvOUJJ6Su0");
        boolean bl = wmjDoorService.updateById(wmjDoor);
        return R.okByRow(bl ? 1 : 0);
    }

    /**
     * 删除微门禁列
     */
    @ApiOperation("删除微门禁列")
    @PreAuthorize("@pms.hasPermission('module:wmjDoor:remove')")
    @SysLog("微门禁列")
    @DeleteMapping("/{ids}")
    public R<Void> remove(@NotEmpty(message = "主键不能为空")  @PathVariable Long[] ids) {
        return R.okByRow(wmjDoorService.removeByIds(Arrays.asList(ids)) ? 1 : 0);
    }
}
